package com.imooc.files.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.imooc.files.resource.FileResource;
import com.imooc.files.service.UploaderService;
import com.imooc.utils.extend.AliyunResource;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * Created with IntelliJ IDEA.
 *
 * @auther Levi
 * @Date: 2021/03/17/22:01
 * @Description:
 */
@Service
public class UploaderServiceImpl implements UploaderService {

    @Autowired
    public FastFileStorageClient fastFileStorageClient;
    @Autowired
    public FileResource fileResource;
    @Autowired
    public AliyunResource aliyunResource;
    @Autowired
    public Sid sid;

    @Override
    public String uploadFdfs(MultipartFile file, String fileExtName) throws IOException {
        StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(),
                fileExtName, null);
        return storePath.getFullPath();
    }

    @Override
    public String uploadOss(MultipartFile file, String userId,
                            String fileExtName) throws Exception{
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint =fileResource.getEndpoint();
// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = aliyunResource.getAccessKeyID();
        String accessKeySecret = aliyunResource.getAccessKeySecret();

// 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

// 填写网络流地址。
        InputStream inputStream = file.getInputStream();
// 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。
        //路径示例  images/abc/usrId/sid随机数.png
        String myObjectName = fileResource.getObjectName() + "/" + userId + "/" +
                sid.nextShort() + "." + fileExtName;
        ossClient.putObject(fileResource.getBuketName(), myObjectName, inputStream);

// 关闭OSSClient。
        ossClient.shutdown();

        return myObjectName;
    }
}
